package com.thoughtworks.shoutbox.client.room;

import java.util.Map;
import java.util.Map.Entry;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.thoughtworks.shoutbox.client.services.ServiceCallback;
import com.thoughtworks.shoutbox.client.services.ShoutingService;
import com.thoughtworks.shoutbox.client.services.ShoutingServiceAsync;

public class RoomListView extends Composite {
	private ShoutingServiceAsync service = GWT.create(ShoutingService.class);

	private RoomEntranceListener roomEntranceListener;
	private VerticalPanel rootPanel;

	public RoomListView() {
		rootPanel = new VerticalPanel();
		initWidget(rootPanel);
	}

	public RoomEntranceListener getRoomListener() {
		return roomEntranceListener;
	}

	public void setRoomListener(RoomEntranceListener roomEntranceListener) {
		this.roomEntranceListener = roomEntranceListener;
	}

	public void showRooms(Map<String, String> roomIdAndNameMap) {
		rootPanel.clear();
		for (Entry<String, String> roomIdAndName : roomIdAndNameMap.entrySet()) {
			Anchor anchor = new Anchor(roomIdAndName.getValue());
			anchor.addClickHandler(enterRoomListener(roomIdAndName.getKey(), roomIdAndName.getValue()));
			rootPanel.add(anchor);
		}
	}


	private ClickHandler enterRoomListener(final String roomId, final String roomName) {
		return new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				roomEntranceListener.enterRoom(roomId, roomName);
			}
		};
	}

	public void reloadRooms() {
		service.getAllRooms(new ServiceCallback<Map<String,String>>() {
			@Override
			public void onSuccess(Map<String, String> result) {
				showRooms(result);
			}
		});
	}

}
